package edu.hawaii.ics.pjdb.worker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TTransportException;

public class WorkerPool {
    protected static class Worker implements Runnable {
        private final TServer server;

        public Worker(TServer server) {
            this.server = server;
        }

        @Override
        public void run() {
            server.serve();
        }

        public void stop() {
            server.stop();
        }
    }

    private final ExecutorService threadPool;
    private final List<Worker> workers = new ArrayList<Worker>();

    public WorkerPool() {
        this.threadPool = Executors.newCachedThreadPool();
    }

    public WorkerPool(ExecutorService service) {
        this.threadPool = service;
    }

    public void addWorker(int port) throws TTransportException {
        TServer server = WorkerHelper.createWorker(port);
        Worker worker = new Worker(server);
        workers.add(worker);
        threadPool.execute(worker);
    }

    public void killWorkers() {
        for (Worker worker : workers) {
            worker.stop();
        }
    }
}
